<?php
// +----------------------------------------------------------------------
// | ProjectName : domall
// +----------------------------------------------------------------------
// | Description :  购物车
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.idowe.com All rights reserved.
// +----------------------------------------------------------------------
// | Authors : Johhny <chenjf@idowe.com>  Date : 2016-03-03
// +----------------------------------------------------------------------
namespace app\index\controller;

class Cart extends Base
{
    /**
     * 购物车首页
     * @author Johhny <chenjf@idowe.com>
     * @return string
     */
    public function index(){
        $where['buyer_id'] = $this->user_info['member_id'];
        $cart_list = M('cart')->where($where)->select();
        $this->assign('cart_list',$cart_list);
        return $this->display();
    }

    /**
     * 加入到购物车中
     * @author Johhny <chenjf@idowe.com>
     */
    public function add(){
        if(IS_POST){
            $goods_id = $_POST['goods_id'];
            $quantity = intval($_POST['quantity']);
            if ($goods_id <= 0) return;
            $goods_info = M('goods')->where(array('goods_id'=>$goods_id))->find();
            //判断商品是否已存在购物车中
            $where['goods_id'] = $goods_id;
            $where['buyer_id'] = $this->user_info['member_id'];
            $check_cart = M('cart')->where($where)->find();
            if($check_cart){
                M('cart')->where($where)->setInc('goods_num',$quantity);
            }else{
                $array    = array();
                $array['buyer_id']  = $this->user_info['member_id'];
                $array['store_id']  = $goods_info['store_id'];
                $array['goods_id']  = $goods_info['goods_id'];
                $array['goods_name'] = $goods_info['goods_name'];
                $array['goods_price'] = $goods_info['goods_price'];
                $array['goods_num']   = $quantity;
                $array['goods_image'] = $goods_info['goods_image'];
                $array['store_name'] = $goods_info['store_name'];
                $array['bl_id'] = isset($goods_info['bl_id']) ? $goods_info['bl_id'] : 0;
                M('cart')->add($array);
            }
            $where['buyer_id'] = $this->user_info['member_id'];
            $cart_info = M('cart')->where($where)->select();
            $cart_info_price = 0;
            foreach($cart_info as $item){
                $cart_info_price = $cart_info_price+ $item['goods_num']*$item['goods_price'];
            }
            $cart_info = array('cart_info_price'=>$cart_info_price);
            return json_encode($cart_info);
        }
    }
}
